package com.ghxxzx.daglcustom.business_form.service;

import org.activiti.engine.HistoryService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.tmsps.ne4spring.base.BaseService;
import org.tmsps.ne4spring.utils.ChkUtil;

import java.util.List;

/**
 * 表单去重
 * 
 * @author Administrator
 *
 */
@Service
public class FormDuplicateService extends BaseService {

	@Autowired
	private TaskService taskService;
	@Autowired
	private HistoryService historyService;

	// 表单去重
	public void doDuplicateTask(String processInstanceId) {
		// 1.找到历史task
		List<HistoricTaskInstance> listHistory = historyService.createHistoricTaskInstanceQuery()
				.processInstanceId(processInstanceId).orderByTaskCreateTime().desc().list();
		if (listHistory.size() <= 1) {
			return;
		}
		HistoricTaskInstance preTask = listHistory.get(1);
		if (ChkUtil.isNull(preTask.getAssignee())) {
			// 执行人为空
			return;
		}

		// 2. 找到当前task
		List<Task> list = taskService.createTaskQuery().processInstanceId(processInstanceId).list();
		// 最后一个节点等于0; 会签任务 多task 直接返回
		if (list.size() == 0 || list.size() > 1) {
			return;
		}
		Task task = list.get(0);
		if (ChkUtil.isNull(task.getAssignee())) {
			// 执行人为空
			return;
		}
		System.err.println(preTask.getId());
		System.err.println(task.getId());

		// 3.对比执行人是否一样
		if (preTask.getAssignee().equals(task.getAssignee())) {
			logger.info("检测到执行人相同:{},自动完成审批.", preTask.getAssignee());
			// 关闭task
			taskService.complete(task.getId());
		}
	}

}
